<?php

//defined( '_VALID_MOS' ) or die( 'Restricted access' );

if ( $_GET["id"] == "" )
	exit;

define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__) . "/../t2" );
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();

$mainframe->route();
$user =& JFactory::getUser();


try {
	$id=intval($_GET["id"]);
}
catch (Exception $e ) 
{
	exit;
}

$eventid=$id;
require "jumi_dbconfig.php";

$this_username = $user->username;
$this_useremail = $user->email;
$this_userid = $user->id;
$this_usertype = $user->usertype;


function SendCommandSF($command,$para1,$para2 ) {
    switch ($command)
    {
	case "POST":
		return PostComment(urldecode($para1),$para2);	
		break;
	case "UP":
		return Vote("UP",$para1);	
		break;
	case "DOWN":
		return Vote("DOWN",$para1);	
		break;
	case "HIDE":
		return Admin("HIDE",$para1);	
		break;
	case "HIDESTORY":
		return Admin("HIDESTORY",$para1);	
		break;


    }
    return "OK";
}

function Admin($mode, $commentid)
{
	global $this_username;
	global $this_userid;
	global $eventid;
	global $db;
	if ($this_username =="" )
	{
		return "NOTLOGIN";
	}
	switch ( $mode )
	{
		case "HIDE":
			$published=0;
			$query = sprintf("update comment set published=%d where id=%d or parentid=%d ",$published,$commentid,$commentid);
			$return="ADMINOK:$commentid";
			break;
		case "SHOW":
			$published=1;
			$query = sprintf("update comment set published=%d where id=%d or parentid=%d ",$published,$commentid,$commentid);
			$return="ADMINOK:$commentid";
			break;
		case "HIDESTORY":
			$published=0;
			$query = sprintf("update critizethis_story set published=%d where id=%d ",$published,$commentid);
			$return="ADMINSTORYOK:$commentid";
			break;
	} 
	
	try  {
		$result = mysql_query("$query",$db) ;
	}
 	catch (Exception $e)
	{
		return "ADMINFAILED:$commentid";
	}
	
	return $return;
}

function Vote($mode, $commentid)
{
	global $this_username;
	global $this_userid;
	global $eventid;
	global $db;
	if ($this_username =="" )
	{
		return "NOTLOGIN";
	}
	switch ( $mode )
	{
		case "UP":
			$up=1;
			$down=0;
			break;
		case "DOWN":
			$up=0;
			$down=1;
	} 
	
	$query= "delete from comment_vote where commentid=$commentid and userid=$this_userid ";
	$result = mysql_query("$query",$db) ;
	$query = sprintf("INSERT INTO comment_vote (commentid,userid,up_vote,down_vote) VALUES ('%d','%d','%d','%d')",
		$commentid,$this_userid,$up,$down );
	try  {
		$result = mysql_query("$query",$db) ;
	}
 	catch (Exception $e)
	{
		return "VOTEFAILED:$commentid";
	}
	return "VOTEOK:$commentid";
}
function PostComment($comment,$commentid)
{
	global $this_username;
	global $this_userid;
	global $eventid;
	global $db;
	if ($this_username =="" )
	{
		return "NOTLOGIN";
	}
	if ( $commentid<=0) //	first post
	{
		$query = sprintf("INSERT INTO comment (eventid,userid,username,comment) VALUES ('%d','%d','%s','%s')",
			mysql_real_escape_string($eventid),
			mysql_real_escape_string($this_userid),
			mysql_real_escape_string($this_username),
			mysql_real_escape_string($comment) );
	}
	else // reply
	{
		$query = sprintf("INSERT INTO comment (eventid,parentid,userid,username,comment) VALUES (%d,%d,%d,'%s','%s')",
			mysql_real_escape_string($eventid),
			mysql_real_escape_string($commentid),
			mysql_real_escape_string($this_userid),
			mysql_real_escape_string($this_username),
			mysql_real_escape_string($comment) );
	}
	try  {
		$result = mysql_query("$query",$db) or die ("Error in query: $query. " . mysql_error());
	}
 	catch (Exception $e)
	{
		return "FAILED";
	}
	return "OK";
}


    require("sajax/sajax.php");
//    $sajax_debug_mode = true;

    $sajax_failure_redirect = "http://sajax.info/sajaxfail.html";
    sajax_export("SendCommandSF");
    sajax_handle_client_request();


?>
<html>
<head>
<link rel=StyleSheet href="criticizethis.css" type="text/css">

</head>

<script type="text/javascript" src="sajax/json2.stringify.js"></script>
<script type="text/javascript" src="sajax/json_stringify.js"></script>
<script type="text/javascript" src="sajax/json_parse_state.js"></script>
<script type="text/javascript" src="sajax/sajax.js"></script>

<script>

<?
	sajax_show_javascript();
?>
function FIND(item) {
   if( window.mmIsOpera ) return(document.getElementById(item));
   if (document.all) return(document.all[item]);
   if (document.getElementById) return(document.getElementById(item));
   return(false);
};

function SendCommand_callback( result) {
	
        if ( result == "NOTLOGIN" )
        {
		mymessage.innerHTML="Please login first.";
        }
        if ( result == "OK" )
        {
		mycomment.value="";
		mymessage.innerHTML="Comment submitted";
		window.location.reload();
        }
        if ( result.indexOf("VOTEOK:")== 0 )
        {
		start=result.indexOf (":")+1;
		commentid=result.substr(start,result.length-start );
		obj=FIND("mymessage_" + commentid );
		//alert(commentid);
		obj.innerHTML="Vote OK. ";
		window.location.reload();
	}
        if ( result.indexOf("VOTEFAILED:")== 0 )
        {
		start=result.indexOf (":")+1;
		commentid=result.substr(start,result.length-start );
		obj=FIND("mymessage_" + commentid );
		obj.innerHTML="Vote failed. You can't vote twice on same comment.";
	}
        if ( result.indexOf("ADMINOK:")== 0 )
        {
		start=result.indexOf (":")+1;
		commentid=result.substr(start,result.length-start );
		obj=FIND("mymessage_" + commentid );
		//alert(commentid);
		obj.innerHTML="Comment hidden. ";
		window.location.reload();
	}
        if ( result.indexOf("ADMINSTORYOK:")== 0 )
	{
		mymessage.innerHTML="Story deleted.";
		window.location="latest_stories.php";
	}
}

function SendCommand(command, para1,para2)
{
        x_SendCommandSF(command, para1,para2, SendCommand_callback);
}
function VoteUp( commentid)
{
	SendCommand("UP",commentid,"");
}

function VoteDown( commentid)
{
	SendCommand("DOWN",commentid,"");
}
function ShowReply( commentid)
{
	div=FIND("divreply_"+commentid);
	div.innerHTML="<br>Reply comment: <br><textarea id=ta_reply"+ commentid + " cols=90 rows=3></textarea><br><input type=button onclick='javascript:HideReplyWindow("+ commentid +")' value=Cancel><input type=button onclick='javascript:ReplyComment("+ commentid + ")' value=Post>";
}

function HideReplyWindow( commentid)
{
	div=FIND("divreply_"+commentid);
	div.innerHTML="";

}

function Hide( commentid)
{
	SendCommand("HIDE",commentid,"");
}

function HideStory( storyid)
{
	SendCommand("HIDESTORY",storyid,"");
}

function ReplyComment(commentid)
{
	obj=FIND("ta_reply" + commentid);
	msg=FIND("mymessage_" + commentid);
	if ( obj.value =="" )
	{
		msg.innerHTML="please type in a reply, then submit.";
		return;
	}
	if ( obj.value.length >1000  )
	{
		msg.innerHTML="Comment too long.";
		return;
	}
	SendCommand("POST",encodeURI(obj.value),commentid );
}

function PostComment()
{
	if ( mycomment.value =="" )
	{
		mymessage.innerHTML="please type in a comment, then submit.";
		return;
	}
	if ( mycomment.value.length >1000  )
	{
		mymessage.innerHTML="Comment too long.";
		return;
	}
	SendCommand("POST",encodeURI (mycomment.value) ,0 );
}

</script>

<?
$query = "SELECT *, date_format(datecreated,'%Y-%m-%d %H:%i') as date1 FROM critizethis_story where id = '$id' and published=1 order by id desc limit 0,1";

$result = mysql_query($query,$db) or die (" died on query: ". $query);
$myrow = mysql_fetch_array($result);
$story_id = stripslashes($myrow["id"]);
$story_desc = stripslashes($myrow["description"]);
$story_title = stripslashes($myrow["title"]);
$story_datecreated = stripslashes($myrow["date1"]);
$story_link= stripslashes($myrow["link"]);
?>
<body>


<a href="latest_stories.php"><h1><font color="#666666">Return to Criticize This start page</font></h1></a>
<table width="100%">

<?
	if ( $this_usertype =="Administrator" ||  $this_usertype =="Super Administrator")
	{
?>
<tr><td>
	<input type="button" onClick="javascript:HideStory(<?=$story_id?>)" value="Delete this Story" /><br>
</td></tr>
<?
	}
?>

<tr><td><h1><font color="#666666"><?=$story_title?></font></h1>

<?
/*
<script type='text/javascript' src='http://therealnews.com/scripts/player/swfobject.js'></script>

  <div id='mediaspace'>This div will be replaced</div>

  <script type='text/javascript'>
  var s1 = new SWFObject('http://therealnews.com/scripts/player/player.swf','ply','890','500','9','#ffffff');
  s1.addParam('allowfullscreen','true');
  s1.addParam('allowscriptaccess','always');
  s1.addParam('wmode','opaque');
  s1.addParam('flashvars','file=http://www.youtube.com/watch?v=<?=$story_link?>');
  s1.write('mediaspace');
</script>
*/

?>

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="890" height="500">
<param name="width" value="890"/>
<param name="height" value="500"/>
<param name="allownetworking" value="internal" />
<param name="enablehref" value="false" />
<param name="allowfullscreen" value="true"/>
<param name="src" value="http://www.youtube.com/v/<?=$story_link?>&autoplay=1&fs=1&showinfo=0&fs=1&rel=0&showsearch=0" />
<embed type="application/x-shockwave-flash" src="http://www.youtube.com/v/<?=$story_link?>&rel=0&autoplay=1&fs=1&showinfo=0&fs=1&hl=en&showsearch=0" width="890" height="500" enablehref="false" allownetworking="internal" allowfullscreen="true"></embed>
</object>


</td></tr>
<tr><td><br><br><h4>Criticize This Story</h4>

<?
	if ( $this_username != "" ) {
?>
<textarea name="mycomment" id="mycomment" cols=108 rows=6></textarea><br><br>
<input type="button" onClick="javascript:PostComment()" value="Submit Your Critique" /><br>
<?
	} else
	{
	
		//$redirectUrl = base64_encode($_SERVER['REQUEST_URI'] );
		$redirectUrl = base64_encode( "/t2/component/content/646?task=view&storyid=$id" );
		//echo "<!-- uri: ". $_SERVER['REQUEST_URI']  ."//-->";

		echo " <h3><font color=\"#666666\">Please <a href=\"http://login.therealnews.com/t2/index.php?option=com_user&view=login&return=$redirectUrl\" target=\"_top\">login</a> first to write a critique.</font></h3>";
	}

?>
<div id=mymessage></div></td></tr>

<tr><td height=20 ><h4></h4></td></tr>
<tr><td><h4>Critiques</h4>
</td></tr>
</table>

<table width="890" border=0>
<?


function PrintRow ( $myrow )
{
	global $this_userid, $this_usertype;
	
	
        $comment_comment= stripslashes($myrow["comment"]);
        $comment_id = stripslashes($myrow["id"]);
        $comment_parentid = stripslashes($myrow["parentid"]);
        $comment_userid = stripslashes($myrow["userid"]);
        $comment_username = stripslashes($myrow["username"]);
        $comment_datecreated = stripslashes($myrow["date1"]);
        $comment_up= stripslashes($myrow["up_vote"]);
        $comment_down= stripslashes($myrow["down_vote"]);


        if ( $comment_parentid ==0  )
        {
                $divpad="<div>";
        }
	else {
                $divpad="<div style=\"padding:0px 0px 0px 60px;\">";
	}
	if ( $this_userid !="" )
	{
	        echo "$divpad<table ><tr><td ><a href='Javascript:VoteUp( $comment_id ) ' ><img src=\"/scripts/images/voteup.png\" border=\"0\"></a></td><td ><font color=\"#939393\" size=\"+3\">$comment_up</font></b></td><td rowspan=\"2\">
		
			$comment_comment</b><br><font size=\"-2\"><i>$comment_username</i>&nbsp; $comment_datecreated</font>
			
			";

		if ( $comment_parentid ==""   )
		{
		        echo "<a href='Javascript:ShowReply( $comment_id) ' >&nbsp;&nbsp;&nbsp;reply</a> ";
		}
		if ( $this_usertype =="Administrator" ||  $this_usertype =="Super Administrator")
		{
		        echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		        echo "<a href='Javascript:Hide( $comment_id) ' >delete</a><p> ";
		}


		echo "<div id=divreply_" . $comment_id . "></div><div id=mymessage_" . $comment_id . "></div></td></tr>
		
			<tr><td width=\"40\"> <a href='Javascript:VoteDown( $comment_id) ' ><img src=\"/scripts/images/votedown.png\" border=\"0\"></a></td><td><font color=\"#939393\" size=\"+3\">$comment_down</font></b>
		
			</td></tr></table><hr class='dots'>";
	}
	else
	{

        	echo "$divpad<table ><tr><td ><img src=\"/scripts/images/voteup.png\" border=\"0\"></td><td ><font color=\"#939393\" size=\"+3\">$comment_up</font></b></td><td rowspan=\"2\">
		
			$comment_comment</b><br><font size=\"-2\"><i>$comment_username</i>&nbsp; $comment_datecreated</font>
		
			";

		echo "<div id=divreply_" . $comment_id . "></div><div id=mymessage_" . $comment_id . "></div></td></tr>
		
			<tr><td width=\"40\"> <img src=\"/scripts/images/votedown.png\" border=\"0\"></td><td><font color=\"#939393\" size=\"+3\">$comment_down</font></b>
		
			</td></tr></table><hr class='dots'>";

	}	
	echo "</div>";

}


$query = "SELECT a.id,parentid,a.userid,username,comment,date_format(datecreated,'%Y-%m-%d %H:%i') as date1,ifnull(sum( b.up_vote),0)as up_vote,ifnull(sum( b.down_vote),0)as down_vote FROM comment a left join comment_vote b on a.id=b.commentid where eventid = '$eventid' and published=1 and parentid is null group by a.id order by ifnull(sum(b.up_vote),0)-ifnull(sum(b.down_vote),0) desc,a.id desc limit 0,50";
$result = mysql_query($query,$db) or die (" died on query: ". $query);


while ($myrow = mysql_fetch_array($result))
{

	PrintRow($myrow);
        $comment_id = stripslashes($myrow["id"]);

	$query1 = "SELECT a.id,parentid,a.userid,username,comment,date_format(datecreated,'%Y-%m-%d %H:%i') as date1,ifnull(sum( b.up_vote),0)as up_vote,ifnull(sum( b.down_vote),0)as down_vote FROM comment a left join comment_vote b on a.id=b.commentid where eventid = '$eventid' and published=1 and parentid =$comment_id group by a.id order by ifnull(sum(b.up_vote),0)-ifnull(sum(b.down_vote),0) desc,a.id desc limit 0,50";
	$result1 = mysql_query($query1,$db) or die (" died on query: ". $query);
	while ($myrow1 = mysql_fetch_array($result1))
	{
		PrintRow($myrow1);
	}

?>

</div></td></tr>
<?
}
?>
</table>
</body>
